package cn.yzking.studentmanagement;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Button;

import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputEditText;

import cn.yzking.studentmanagement.databinding.ActivityRegisterBinding;
import cn.yzking.studentmanagement.utils.MyDBHelper;

public class RegisterActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityRegisterBinding binding = ActivityRegisterBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        TextInputEditText usernameEditText = binding.etUsername;
        TextInputEditText passwordEditText = binding.etPassword;
        TextInputEditText repeatPasswordEditText = binding.etRepeatPassword;
        Button registerButton = binding.buttonRegister;

        registerButton.setOnClickListener(v -> {
            String username = usernameEditText.getText().toString().trim();
            String password = passwordEditText.getText().toString();
            String repeatPassword = repeatPasswordEditText.getText().toString();
            if (password.equals(repeatPassword)) {
                MyDBHelper helper = new MyDBHelper(this);
                if (helper.userRegister(username, password)) {
                    new MaterialAlertDialogBuilder(this)
                            .setIcon(R.drawable.ic_success)
                            .setTitle("注册成功")
                            .setMessage("[" + username + "]注册成功!")
                            .setPositiveButton("返回登陆", null)
                            .setOnDismissListener(dialog -> finish())
                            .show();
                } else {
                    new MaterialAlertDialogBuilder(this)
                            .setIcon(R.drawable.ic_error)
                            .setTitle("注册失败")
                            .setMessage("账号[" + username + "]已存在!")
                            .setNegativeButton("确定", null)
                            .show();
                }
            } else {
                new MaterialAlertDialogBuilder(this)
                        .setIcon(R.drawable.ic_error)
                        .setTitle("注册失败")
                        .setMessage("两次输入的密码不一致,请重新输入!")
                        .setNegativeButton("确定", null)
                        .show();
            }
        });
    }
}